<template>
  <drawer :show="show" :title="'筛选'" :showBtns="true" :confirmText="comfireText" :cancelText="'重置'" @close="bindClose"
    @confirm="submit" @cancel="handleReset">
    <!-- 全部选项 -->
    <view class="filter-all-section" v-if="!isShowDate && nodeAll">
      <filter-item :label="'全部'" :options="[]" :value="allChecked ? ['all'] : []" :multiple="false"
        @change="chooseAll" />
    </view>

    <!-- 日期筛选 -->
    <view class="filter-date-section" v-if="isShowDate">
      <filter-item :label="'计划时间'" :options="dateOptions" :value="dateValue2" :multiple="false"
        :customOption="{ label: '自定义', value: 'custom' }" :customSelected="isCustomDate2" @change="handleDateChange2"
        @custom-select="openDatePicker2" />

      <filter-item :label="'完成时间'" :options="dateOptions" :value="dateValue1" :multiple="false"
        :customOption="{ label: '自定义', value: 'custom' }" :customSelected="isCustomDate1" @change="handleDateChange1"
        @custom-select="openDatePicker1" />
    </view>

    <!-- 筛选项列表 -->
    <view v-for="(item, index) in filteredFilterList" :key="index" class="filter-section">
      <filter-item :tipText="item.key === 'overdue' ? '仅年审梯保养任务参与判断是否逾期' : ''" :label="item.title" :options="(showMap && showMap[item.key] && showMap[item.key].flag) ? item.list.map(it => ({ label: it.name, value: it.value })) : item.list.map(it => ({ label: it.name, value: it.value })).slice(0,6)"
        :value="getFilterValue(item.key)" :multiple="!contractState" :show="true"
        @change="(value) => handleFilterChange(item.key, value)" />
     
      <!-- 显示更多/收起 -->
      <view v-if="isShowMoreTag(item.list, item.key)" @click="showMore(item)" class="more-tag">
        <text>{{ getShowMoreText(item.key) }}</text>
        <image class="more-img"
          :src="getShowMoreIcon(item.key)" />
      </view>
    </view>

    <!-- 日期选择器弹窗 -->
    <time-select v-if="showTimeSelect" :defTime="currentDateRange" :beforeToday="true" :isChooseToday="true"
      @close="closeDatePicker" />
  </drawer>
</template>

<script>
import Drawer from './drawer.vue';
import FilterItem from './filter-item.vue';
import TimeSelect from '@/pages/index/components/timeSelect.vue';

export default {
	name: 'filter-drawer',
	components: {
		Drawer,
		FilterItem,
		TimeSelect,
	},
	data() {
		return {
			choosed: {},
			allChecked: false,
			showTimeSelect: false,
			currentDateType: '',
			showMap: {},
			dateOptions: [
				{ label: '今天', value: 1 },
				{ label: '近7天', value: 7 },
				{ label: '近30天', value: 30 },
				{ label: '近3个月', value: 90 },
				{ label: '近6个月', value: 180 },
				{ label: '本年', value: 9 },
				{ label: '后6个月', value: 8 },
			],
			chooseTime: {
				planBeginDate: '',
				planEndDate: '',
				startTime: '',
				endTime: '',
				value: '',
				value2: '',
			},
		};
	},
	props: {
		chooseData: {
			type: Object,
			default: () => ({}),
		},
		border: {
			type: Boolean,
			default: false,
		},
		filterList: {
			type: Array,
			default: () => [],
		},
		show: {
			type: Boolean,
			default: false,
		},
		comfireText: {
			type: String,
			default: '确认',
		},
		keyMap: {
			type: Object,
			default: () => ({}),
		},
		contractState: {
			type: Boolean,
			default: false,
		},
		isShowArr: {
			type: Number,
			default: 1,
		},
		isShowDate: {
			type: Boolean,
			default: false,
		},
		noPadding: {
			type: Boolean,
			default: false,
		},
		nodeAll:{
			type: Boolean,
			default: true,
		}
	},
	computed: {
		// 日期筛选值
		dateValue1() {
			return this.chooseTime.value ? [this.chooseTime.value] : [];
		},
		dateValue2() {
			return this.chooseTime.value2 ? [this.chooseTime.value2] : [];
		},
		// 是否为自定义日期
		isCustomDate1() {
			return this.chooseTime.startTime && this.chooseTime.endTime && !this.dateValue1.length;
		},
		isCustomDate2() {
			return this.chooseTime.planBeginDate && this.chooseTime.planEndDate && !this.dateValue2.length;
		},
		// 当前日期范围
		currentDateRange() {
			if (this.currentDateType === 'plan') {
				return [this.chooseTime.planBeginDate, this.chooseTime.planEndDate];
			} else {
				return [this.chooseTime.startTime, this.chooseTime.endTime];
			}
		},
		// 过滤后的筛选列表
		filteredFilterList() {
			return this.filterList.filter(item => this.fitlerContract(item));
		}
	},
	watch: {
		keyMap(val) {
			this.showMap = val;
		},
		chooseData: {
			handler(val) {
				this.choosed = { ...val };
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		initData(obj) {
      		this.choosed = obj;
    	},
		// 获取筛选值
		getFilterValue(key) {
			return this.choosed[key] || [];
		},

		// 处理筛选变化
		handleFilterChange(key, value) {
			this.choosed[key] = value;
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
			});
			this.$forceUpdate();
		},

		// 处理日期变化
		handleDateChange1(value) {
			if (value.length > 0) {
				const dateValue = value[0];
				this.handleDateChange(dateValue, 'complete');
			}
		},

		handleDateChange2(value) {
			if (value.length > 0) {
				const dateValue = value[0];
				this.handleDateChange(dateValue, 'plan');
			}
		},

		// 统一处理日期变化
		handleDateChange(dateValue, type) {
			if (type === 'plan') {
				this.chooseTime.value2 = dateValue;
				if (dateValue === 8 || dateValue === 9) {
					this.handleSpecialDate(dateValue);
				}
			} else {
				this.chooseTime.value = dateValue;
			}

			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				...this.chooseTime
			});
		},

		// 处理特殊日期（后6个月、本年）
		handleSpecialDate(dateValue) {
			const now = new Date();
			if (dateValue === 8) {
				const startDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
				const endDate = new Date(now.getFullYear(), now.getMonth() + 7, 0);
				this.chooseTime.planBeginDate = this.formatDate(startDate);
				this.chooseTime.planEndDate = this.formatDate(endDate);
			} else if (dateValue === 9) {
				const startDate = new Date(now.getFullYear(), 0, 1);
				const endDate = new Date(now.getFullYear(), 11, 31);
				this.chooseTime.planBeginDate = this.formatDate(startDate);
				this.chooseTime.planEndDate = this.formatDate(endDate);
			}
		},

		// 打开日期选择器
		openDatePicker1() {
			this.currentDateType = 'complete';
			this.showTimeSelect = true;
		},

		openDatePicker2() {
			this.currentDateType = 'plan';
			this.showTimeSelect = true;
		},

		// 关闭日期选择器
		closeDatePicker(res) {
			this.showTimeSelect = false;
			if (res && res.startTime && res.endTime) {
				if (this.currentDateType === 'plan') {
					this.chooseTime.planBeginDate = res.startTime;
					this.chooseTime.planEndDate = res.endTime;
					this.chooseTime.value2 = '';
				} else {
					this.chooseTime.startTime = res.startTime;
					this.chooseTime.endTime = res.endTime;
					this.chooseTime.value = '';
				}

				this.$emit('chooseTag', {
					allChecked: this.allChecked,
					choosed: this.choosed,
					...this.chooseTime
				});
			}
		},

		// 全选
		chooseAll() {
			this.choosed = {};
			this.allChecked = !this.allChecked;
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
			});
		},

		// 确定
		submit() {
			this.$emit('submit', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				keyMap: this.showMap,
				dateObj: { ...this.chooseTime },
			});
		},

		// 重置
		handleReset() {
			this.choosed = {};
			this.allChecked = false;
			this.chooseTime = {
				planBeginDate: '',
				planEndDate: '',
				startTime: '',
				endTime: '',
				value: '',
				value2: '',
			};
			this.$emit('chooseTag', {
				allChecked: false,
				choosed: this.choosed
			});
		},

		// 关闭
		bindClose() {
			this.$emit('closed', 1);
		},

		// 显示更多标签
		showMore(item) {
			if (this.showMap[item.key]) {
				this.showMap[item.key].flag = !this.showMap[item.key].flag;
			}
		},

		// 判断是否显示更多
		isShowMoreTag(list, key) {
			if (!this.showMap[key]) return false;
			return list.length > 6;
		},

		// 合同筛选条件
		fitlerContract(item) {
			if (item.key === 'contractStatus') {
				return this.findRoute('mystatistics_contract');
			}
			if (item.key === 'contractStatusT' && this.isShowArr === 1) {
				return false;
			}
			return true;
		},

		// 格式化日期
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},

		// 获取显示更多文本
		getShowMoreText(key) {
			return this.showMap[key] && this.showMap[key].flag ? '收起' : '显示更多';
		},

		// 获取显示更多图标
		getShowMoreIcon(key) {
			return this.showMap[key] && this.showMap[key].flag ? require('@/static/images/maintain/sq.png') : require('@/static/images/maintain/zk.png');
		}
	},
};
</script>

<style lang="scss" scoped>
.filter-all-section,
.filter-date-section,
.filter-section {
  // padding: 20rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.filter-tips {
  padding: 10rpx 0;
  font-size: 24rpx;
  color: #999;

  &-text {
    color: #999999;
    font-size: 12px;
    font-weight: normal;
  }
}

.more-tag {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0 10rpx;
  color: #0091ff;
  font-size: 24rpx;

  .more-img {
    width: 24rpx;
    height: 24rpx;
    margin-left: 8rpx;
  }
}
</style>
